package com.student.Activitys.activity.base;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.student.Activitys.utils.ACache;
import com.student.Activitys.utils.Constant;
import com.student.Activitys.utils.NetUtils;
import com.student.Activitys.utils.PermissionUtils;
import com.student.Activitys.utils.UiUtil;
import com.zhy.autolayout.AutoLayoutActivity;

import org.simple.eventbus.EventBus;

import butterknife.ButterKnife;


/**
 * 项目名称：
 * 类描述：父类公用Activity方法
 * 创建人：张飞祥
 * 创建时间：2017/9/18 下午2:17
 * 修改人：张飞祥
 * 修改时间：2017/9/18 下午2:17
 * 修改备注：
 */
public abstract class BaseActivity extends AutoLayoutActivity  implements ActivityCompat.OnRequestPermissionsResultCallback{

    //缓存管理
    protected ACache mACache;
    //网络请求加载进度
    protected static MaterialDialog timeDailog;
    //网络请求提示页面
    protected static MaterialDialog dialog;
    //网络请求最高等待时间
    protected int timeSecond = 10; // 总秒数
    //是否检查设置页面返回 flag;
    protected boolean falg = false;
    //当前 学号
    protected String xh = null;
    //权限申请
    PermissionUtils.PermissionGrant mPermissionGrant;
    //权限回调
    private OnPermissionListener OnPermissionListener;

    protected abstract void initUI();

    protected abstract void initData();

    //无数据显示页面
    protected abstract void getNotData();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mACache = ACache.get(this);
        Fresco.initialize(this);
        xh = mACache.getAsString(Constant.USER_XH);
        initUI();
        initData();
    }

    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        this.injectViews();
    }


    public void setContentView(View view, ViewGroup.LayoutParams params) {
        super.setContentView(view, params);
        this.injectViews();
    }


    public void setContentView(View view) {
        super.setContentView(view);
        this.injectViews();
    }


    private void injectViews() {
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);


    }

    /**
     * 获取当前 状态栏高度 给view
     * @param view
     */
    protected void setStatusBarHeight(View view){
        //设置状态栏高度
        if (Build.VERSION.SDK_INT >= 19) {
            view.setVisibility(View.VISIBLE);
            //设置状态栏的高度
            LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) view.getLayoutParams(); //取控件textView当前的布局参数
            linearParams.height = UiUtil.getStatusBarHeight(this);// 控件的高强制设成20
            view.setLayoutParams(linearParams); //使设置好的布局参数应用到控件
        }
    }

    @Override
    protected void onDestroy() {
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
        finish();
        //销毁handler
        time_handler.removeCallbacks(time_runnable);
        super.onDestroy();
    }

    /**
     * Handler 网络请求（超时操作）
     */
    protected Handler time_handler = new Handler();
    protected Runnable time_runnable = new Runnable() {
        @Override
        public void run() {
            //开启倒计时
            timeSecond--;
            if (timeSecond == 0) {
                timeDailog.dismiss();
                runOnUiThread(new Runnable() {
                    public void run() {
                        dialog = new MaterialDialog.Builder(BaseActivity.this)
                                .title("数据访问超时")
                                .content("可能与服务器连接不稳定或当前网络环境较差，请检查网络连接相应设置！")
                                .negativeText("取消")
                                .positiveText("检查设置")
                                .onNegative(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(MaterialDialog dialog, DialogAction which) {
                                        //无数据显示页面
                                        getNotData();
                                    }
                                })
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(MaterialDialog dialog, DialogAction which) {
                                        NetUtils.openSetting(BaseActivity.this);
                                        //销毁handler
                                        time_handler.removeCallbacks(time_runnable);
                                        falg = true;
                                    }
                                }).show();
                        // 设置点击屏幕Dialog不消失
                        dialog.setCanceledOnTouchOutside(false);
                        //取消Back键监听
                        dialog.setCancelable(false);
                    }
                });
            }
            time_handler.postDelayed(this, 1000);
        }
    };

    /**
     * 显示加载dialog
     */
    public void initShowTimeDialog(String content, Activity activity) {
        //倒计时
        timeSecond = 10;
        //开启倒计时线程
        time_handler.postDelayed(time_runnable, 1000);
        //加载进度
        timeDailog = new MaterialDialog.Builder(activity)
                .content(content)
                .progress(true, 0)
                .show();
        // 设置点击屏幕Dialog不消失
        timeDailog.setCanceledOnTouchOutside(false);
        //取消Back键监听
        timeDailog.setCancelable(false);
    }

    /**
     *
     * 权限处理监听
     * @param OnPermissionListener
     */
    public void setOnPermissionListener(OnPermissionListener OnPermissionListener){
        this.OnPermissionListener  = OnPermissionListener;
    }
    public interface OnPermissionListener{
        void openIntent();
    }

    //权限请求
    public void openPermission(int[] code_permission){

        mPermissionGrant = new PermissionUtils.PermissionGrant() {
            @Override
            public void onPermissionGranted(int requestCode) {
                if(OnPermissionListener!=null){
                    OnPermissionListener.openIntent();
                }
            }
        };
        if(code_permission.length<=0){
            return;
        } else if(code_permission.length==1){
            PermissionUtils.requestPermission(BaseActivity.this, code_permission[0], mPermissionGrant);
        }else {
            PermissionUtils.requestMultiPermissions(BaseActivity.this,code_permission,mPermissionGrant);
        }

    }
    //请求权限回调方法（必须实现OnRequestPermissionsResultCallback接口)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.requestPermissionsResult(BaseActivity.this, requestCode, permissions, grantResults, mPermissionGrant);
    }
}
